#include "widgets/dashboard.h"
#include "widgets/tomatowidget.h"
#include <QVBoxLayout>
#include <QFrame>
#include <QApplication>
#include <QScreen>
#include <QCloseEvent>
#include <QPainter>
#include <QPushButton>
#include <QtCharts>
#include <QtCharts/QPieSeries>
#include <QtCharts/QValueAxis>
#include <QtCharts/QChartView> //显示图表
#include "widgets/progressbarwidget.h"
#include <QSettings>
#include <QDate>
#include "services/window/windowservice.h"
#include "eventreceiver.h"
#include <QStandardItemModel>
#include <QStandardItem>
#include "widgets/whitenoiseplayer.h"
#include "widgets/whitenoise.h"
using namespace QtCharts;
using dpfservice::WindowService;
DashBoard::DashBoard(TomatoClockButton *clock, QWidget *parent) : QWidget(parent), clock(clock)
{
    initUI();
}

void DashBoard::initUI()
{

    setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    setContentsMargins(0, 0, 0, 0);

    // 主布局
    auto mainLayout = new QVBoxLayout(this);

    // 上部布局
    auto topLayout = new QHBoxLayout();
    topLayout->setAlignment(Qt::AlignVCenter);
    // LOGO
    auto label_icon = new QLabel(this);
    label_icon->setPixmap(QIcon::fromTheme("tomato").pixmap(QSize(30, 30)));
    label_icon->setAlignment(Qt::AlignVCenter);
    topLayout->addWidget(label_icon);
    mainLayout->addLayout(topLayout);
    mainLayout->setStretchFactor(topLayout, 1);

    auto middleLayout = new QVBoxLayout();
    // 初始化时间
    int duration = 25 * 60;
    TomatoClock *tomatoClock = new TomatoClock(duration);
    clock->setText(QTime(0, 0).addSecs(duration).toString("mm:ss"));

    connect(tomatoClock, &TomatoClock::timeUpdated, clock, [=](QString textStr)
            { clock->setText(textStr); });
    middleLayout->addWidget(tomatoClock);
    mainLayout->addLayout(middleLayout);
    mainLayout->setStretchFactor(middleLayout, 1);
    mainLayout->addSpacing(20);

    // 下部布局
    auto bottomLayout = new QVBoxLayout();
    // 数据框
    auto buttonLayout = new QGridLayout();
    for (int i = 0; i < 2; ++i)
    {
        framesData[i] = new DisplayFrame(this);
        buttonLayout->addWidget(framesData[i], i / 2, i % 2);
    }
    initDisplayData();
    // 通过信号-槽机制实时更新专注时长
    connect(tomatoClock, &TomatoClock::timeUpdated, framesData[1], [=]()
            { 
    QSettings *m_iniFile = new QSettings("src/plugins/myClock/data.ini", QSettings::IniFormat);
    QString today_second_str = m_iniFile->value("user_base/stick_second").toString();
    int today_second_int = today_second_str.toInt();
    double hours = static_cast<double>(today_second_int) / 3600.0;
    QString hours_str = QString("%1").arg(hours, 0, 'f', 2);
    framesData[1]->setTopText(hours_str);
    framesData[1]->setBottomText("日专注时长(h)");
    framesData[1]->setBackgroundColor("#c61d53"); });
    QWidget *dataWidget = new QWidget(this);
    dataWidget->setLayout(buttonLayout);
    bottomLayout->addWidget(dataWidget);

    // 白噪音
    // 原始方法实现
    // auto playerWidget = new WhiteNoisePlayer;
    // QMediaPlayer实现
    auto playerWidget= new WhiteNoise;
    bottomLayout->addWidget(playerWidget);

    QWidget *chartWidget = new QWidget(this);

    // 通过信号更新图标数据
    auto chartView = new QChartView(this);
    QChart *charts = chartView->chart(); // 获取QChart对象
    if (charts)
    {
        charts->removeAllSeries();
    }
    connect(EventReceiverProxy::instance(), &EventReceiverProxy::chartUpdated, this, [=]()
            { createChart(chartView); });

    chartWidget->setLayout(new QVBoxLayout());

    chartWidget->layout()->addWidget(chartView);
    bottomLayout->addWidget(chartWidget);
    auto bottomWidget = new QWidget(this);
    bottomWidget->setLayout(bottomLayout);

    bottomLayout->setStretchFactor(playerWidget, 2);
    bottomLayout->setStretchFactor(dataWidget, 2);
    bottomLayout->setStretchFactor(chartWidget, 6);

    mainLayout->addWidget(bottomWidget);
    mainLayout->setStretchFactor(bottomWidget, 8);

    setLayout(mainLayout);
}

void DashBoard::closeEvent(QCloseEvent *event)
{
    // 这里可以添加关闭窗口时的处理逻辑，例如隐藏窗口而不是销毁
    hide();          // 隐藏窗口
    event->ignore(); // 忽略关闭事件，不销毁窗口
}

// 图表初始化
void DashBoard::createChart(QChartView *chartView)
{

    QStringList commonFileExtensions;
    commonFileExtensions << "h" << "cpp" << "c" << "java" << "py" << "js"
                         << "cs" << "sh" << "bat" << "txt" << "json"
                         << "xml" << "html" << "css" << "sql" << "vue";

    // 创建饼图系列
    QPieSeries *series = new QPieSeries();
    QChart *chart = new QChart();
    QSettings *m_iniFile = new QSettings("src/plugins/myClock/data.ini", QSettings::IniFormat);
    // 跳转到chart节点
    m_iniFile->beginGroup("chart");
    QStringList keys = m_iniFile->childKeys();

    for (int i = 0; i < keys.size(); ++i)
    {
        const QString &key = keys[i];
        if (commonFileExtensions.contains(key))
        {
            int value = m_iniFile->value(key).toInt();
            QPieSlice *slice = series->append(key, value);
            slice->setLabelVisible(true); // 设置扇形上显示指标文字
        }
    }

    m_iniFile->endGroup();
    chart->addSeries(series);
    chart->setTitle("工程概况");
    chart->createDefaultAxes();
    chart->legend()->hide();
    chartView->setChart(chart);
    chartView->setMinimumSize(QSize(100, 100));
}

// 数据初始化
void DashBoard::initDisplayData()
{
    QSettings *m_iniFile = new QSettings("src/plugins/myClock/data.ini", QSettings::IniFormat);
    QString today = QDate::currentDate().toString("yyyyMMdd");
    QString dev_day_str = m_iniFile->value("user_base/dev_day").toString();
    QString today_date = m_iniFile->value("user_base/today_date").toString();
    framesData[0]->setTopText(dev_day_str);
    framesData[0]->setBottomText("坚持天数");
    framesData[0]->setBackgroundColor("#233585");

    QString today_second_str = m_iniFile->value("user_base/stick_second").toString();
    int today_second_int = today_second_str.toInt();
    double hours = static_cast<double>(today_second_int) / 3600.0;
    QString hours_str = QString("%1").arg(hours, 0, 'f', 2);
    framesData[1]->setTopText(hours_str);
    framesData[1]->setBottomText("日专注时长(h)");
    framesData[1]->setBackgroundColor("#c61d53");

    // framesData[2]->setTopText("--");
    // framesData[2]->setBottomText("待扩展");
    // framesData[2]->setBackgroundColor("#ff4c00");

    // framesData[3]->setTopText("104");
    // framesData[3]->setBottomText("工程代码量(行)");
    // framesData[3]->setBackgroundColor("#ff9e00");
}

void DashBoard::updateChart()
{

    QChartView *chartView = qobject_cast<QChartView *>(sender());
    if (chartView)
    {
        auto wins = dpfGetService(dpfservice::WindowService);
        wins->notify(0, "12121", "23423", {});
        createChart(chartView); // 重新创建饼图
    }
}